<?php

namespace Addons\Zmphoto\Controller;

use Home\Controller\AddonsController;

class WapController extends AddonsController {

   public function _initialize(){
       $isWeixinBrowser = isWeixinBrowser ();

       if ((empty ( $openid ) || $openid == '-1') && $isWeixinBrowser && $_REQUEST ['openid'] != '-2') {  
       }
       else
       {
           $this->error("请在微信打开!");
       }
         
       // get_openid("ofCONv1WVGN2zjF-lOv-rF_nuTc8");
   }
   
    //选择活动
    public function index(){
        /*获取对应token的活动*/
        $data =D('Addons://Zmphoto/PhotoZmActivity')->getActList();
        $this->assign('data',$data);
        $this->display();
    }

    public function studInfo(){
        $aid = I('aid',0,'intval');
        $data = $this->getActInfo($aid);
        /*获取用户信息并判断用户是否是首次登录*/
        $uinfo = $this->userInfoByopenId($aid);
        $this->assign('info',$uinfo);

        //*根据openid获取用户uid 自动进入打印页面*/
        $openid = get_openid();
        $uid = M('photo_zm_data')->where(array('openid'=>$openid,'token'=>get_token()))->getField('id');
        if($aid == '2'){
             $this->redirect('electron_pic',array('uid'=>$uid));
        }

        /*判断是教师还是学生*/
        if($uinfo['grade'] == 10){
            $this->assign('isteacher',1);
        }

        $this->display();
    }

    /*解除信息绑定*/
    public function removeBand(){
        $id = I('get.id');
        $info = $this->userInfo($id);
        if((int)$info['remove_num'] >= 3) $this->error('解除超过3次，无法再次解除');
        if(!$info['remove_num']){
            $data['remove_num'] = 1;
        }else{
             $data['remove_num'] = (int)$info['remove_num']+1;
        }
       
        $data['openid'] = '';
        $model = D('Addons://Zmphoto/PhotoZmData');
        if($model->update(array('id'=>$id),$data)){
            $this->success('解除成功');
        }else{
            $this->error('请重新绑定!');
        }
    }

    public function first(){
       
        $aid = I('get.aid',0,'intval');
        $data = $this->getActInfo($aid);
        /*已经绑定，跳回活动页*/
        $where['aid'] = $data['id'];
        $where['openid'] = get_openid();
        if($s = D('Addons://Zmphoto/PhotoZmData')->getOne($where))  $this->redirect('studInfo',array('id'=>$data['id'])); 
        unset($where);
        if(IS_POST){
            $model = D('Addons://Zmphoto/PhotoZmData');  
            if($info = $model->create()){
                $where['aid'] = $data['id'];
                $where['card_id'] = $info['card_id']; 
                if(! $s = $model->getOne($where)) $this->error('身份证号码或工号输入错误!');
                if($s['openid']) $this->error('当前身份证或工号已经绑定用户');
                if($model->update($where,array('openid'=>get_openid(),'update_time'=>time(),'mobile'=>$info['mobile']))){
                    $this->success('绑定成功！',addons_url('studInfo',array('id'=>$data['id'])));
                }else{
                    $this->error('请重新绑定!');
                }
            }else{
                $this->error($model->getError());
            }
        }else{
            $this->display();
        }
        
    }

    /*修改学生信息*/
    public function updateInfo(){
        $aid = I('get.aid',0,'intval');
        $data = $this->getActInfo($aid);
        $udata = $this->userInfoByopenId($aid);
        if(IS_POST){

           $model = D('Addons://Zmphoto/PhotoZmData');  
           $mobile = I('post.mobile');
           $no = I('post.no');
           $class = I('post.class');
           if(!$mobile) $this->error('请输入手机号码');
           if(I('get.isteacher')){
           if(!$class) $this->error('请输入部门');
           }else{
            if(!$no) $this->error('请输入学号');
            if(!$class) $this->error('请输入班级');
                $a['no'] = $no;
           }
           if(!preg_match('/^0?(13|14|15|17|18)[0-9]{9}$/',$mobile)) $this->error('手机号码格式错误！');
           $a['mobile'] = $mobile;
           $a['class'] = $class;
           if($model->update(array('id'=>$udata['id']),$a)){
                $this->success('修改成功!',U('studInfo',array('aid'=>$aid)));
           }else{
                $this->error('请重新确定');
           }
        }else{
            $this->assign('isteacher',I('get.isteacher'));
            $this->assign('isupdate',1);
            $this->display('first');
        }
    }

    /*意见反馈*/
    public function infoReview(){
        $model = D('Addons://Zmphoto/PhotoZmReview'); 
        if(IS_POST){
            $datas['content'] = I('post.content');
            $datas['uid'] =get_uid_by_openid();
            $datas['token'] = get_token();
            $datas['create_time'] = time();
            if($model->addData($datas))
            {
                
                $openid = array('oMaeHt1n1n8Kx56D2wjs358gNw-g','oMaeHt9W8QBO3c0-NZ0l6k5Lb3sQ',get_openid());
                $num = count($openid);
                for($i=0;$i<$num;++$i)
                {
                
                   $template = array('touser' => $openid[$i],
                    'template_id' =>"tQ-yACiOFRoxqSfj5eih76XSLP8HmO1jNLZnBDwjRds",
                    'url' =>U('infoReview'),
                    'topcolor' => "#7B68EE",
                    'data' =>array(
                        'keyword1'=>array('value'=>urlencode(I('post.content')),
                            'color'=>"#ff00000",
                        ),
                        'keyword2'=>array('value'=>urlencode(time_format(time())),
                            'color'=>"#ff00000",
                        ),
                        'remark'=>array('value'=>urlencode("\\n感谢您提供的宝贵意见，我们会认真处理您的反馈。！"),
                            'color'=>"#008000",
                        ),
                    )
                    );
                    send_template_message(urldecode(json_encode($template)));
                }
                
                $this->success('意见反馈成功，我们会在五个工作日内回复您',U('studInfo',array('aid'=>$aid)));
            }
            else
            {
                $this->error('请重新确定');
            }
        }else{
             /*获取管理员回复信息*/
             $redata = $model->getListAll('reply_content,review_time,content,create_time',array('uid'=>get_uid_by_openid(),'status'=>array('in','0,1')),null,'review_time DESC');
             $this->assign('redata',$redata);
             $opdata=getWeixinUserInfo(get_openid());
             $this->assign('data',$opdata);
             $this->display();
        }
    }   

    /*学生二维码*/
    public function studCode(){
        $aid = I('get.aid',0,'intval');
        $data = $this->getActInfo($aid);
        $udata= $this->userInfoByopenId($aid,'id,username,no,is_pay'); //获取用户信息
        $this->assign('udata',$udata);  
        $save_path = isset($_GET['save_path'])?$_GET['save_path']:'qrcode/';  //图片存储的绝对路径
        $web_path = isset($_GET['save_path'])?$_GET['web_path']:'qrcode/';        //图片在网页上显示的路径
        $qr_data = isset($_GET['qr_data'])?$_GET['qr_data']:U('studPhoto',array('aid'=>$aid,'uid'=>$udata['id']));
        $qr_level = isset($_GET['qr_level'])?$_GET['qr_level']:'H';
        $qr_size = isset($_GET['qr_size'])?$_GET['qr_size']:'10';
        $save_prefix = isset($_GET['save_prefix'])?$_GET['save_prefix']:'ZETA';
        if($filename = $this->createQRcode($save_path,$qr_data,$qr_level,$qr_size,$save_prefix)){
            $pic = $web_path.$filename;
        }
        $this->assign('pic',$pic);
        $this->display();
    }


    /*摄影师注册*/
        public function photoRe(){
        $aid = I('get.aid',0,'intval');
        $data = $this->getActInfo($aid);
        /*已经绑定，跳回活动页*/
        $where['aid'] = $data['id'];
        $where['openid'] = get_openid();
        $s = D('Addons://Zmphoto/PhotoZmGl')->getOne($where);
        if($s && $s['status']){
            $this->success('你已成功注册!',U('photoIndex',array('aid'=>$aid)));   //成功注册 
            exit;
        }
        if($s && !$s['status']){
            $this->success('你已成功注册，请等待管理员审核!',U('photoIndex',array('aid'=>$aid)));   //成功注册 
            exit;
        } 
        if(IS_POST){
            $model = D('Addons://Zmphoto/PhotoZmGl');  
            if($info = $model->create()){
                $info['openid'] = get_openid();
                $info['token'] = get_token();
                $info['aid'] = $aid;
                if($model->add($info)){
                    $this->success('注册成功!请等待后台审核',U('index'));
                }else{
                    $this->error('请重新注册!');
                }
            }else{
                $this->error($model->getError());
            }
            
        }else{
            $this->display();
        }
        
    }


    /*摄影师登录*/
    public function photoIndex(){
        $aid = I('get.aid',0,'intval');
        $data = $this->getActInfo($aid);    
        $udata = $this->getGlInfo($aid);    //获取摄影师信息
        $this->display();   
    }


    /*摄影师扫描*/
    public function studPhoto(){
        $aid = I('get.aid',0,'intval');
        $uid = I('get.uid',0,'intval');
        $data  = $this->getActInfo($aid);
        $udata = $this->userInfo($uid);  //获取用户信息
        $gdata = $this->getGlInfo($data['id']);  //获取管理员信息
        $this->assign('udata',$udata);
        
        //原图
        $photo_url = M('photo_zm_data')->where('id='.$uid)->find();
        $this->assign('photo',$photo_url);
        //红白蓝
        $electron = M('photo_zm_electron')->where('photo_id='.$uid)->select();
        $this->assign('electron',$electron);
        $this->display();         
        
    }

    /*用户信息确认*/
    public function photoOk(){
        $aid = I('get.aid',0,'intval');
        $uid = I('get.uid',0,'intval');
        $openid = get_openid();
        $data  = $this->getActInfo($aid);
        $udata = $this->userInfo($uid);  //获取用户信息
        if($udata['openid'] != $openid) $this->error('当前用户信息错误!');
        // if(!$udata['no']) $this->error('请先完善用户信息');
        $s['confirm'] = 1;
        $s['confirm_time'] = time();
        $model = D('Addons://Zmphoto/PhotoZmData');
        if($model->update(array('id'=>$uid),$s)){
            $this->success('成功!');
        }else{
            $this->error('失败');
        }
    }





    /*获取活动信息*/
    private function getActInfo($id){
        if(!$id || !$data = D('Addons://Zmphoto/PhotoZmActivity')->getOne(array('id'=>$id)))   $this->error('活动不存在!');
        $now = time();
        if($now<$data['start_time']) $this->error('活动暂未开始');
        if($now>$data['end_time'])   $this->error('活动已经结束');

        return $data;
    }

    /*通过openid获取学生信息*/
    private function userInfoByopenId($aid,$field=''){
        $where['openid'] = get_openid();
        $where['aid'] = $aid;
        /*没值则为首次登录，跳转到绑定页面*/
        $data = D('Addons://Zmphoto/PhotoZmData')->getOne($where,$field);
        if(!$data){
            $this->redirect('first',array('aid'=>$aid));
        }
        return $data;
    }


    /*获取用户信息*/
    private function userInfo($id){
        if(!$id || !$data = D('Addons://Zmphoto/PhotoZmData')->getOne(array('id'=>$id)))   $this->error('用户不存在!');
        return $data;
    }

    /*判断当前摄影师身份*/
    private function getGlInfo($aid){
        $openid = get_openid();
        if(!$aid || !$data = D('Addons://Zmphoto/PhotoZmGl')->getOne(array('aid'=>$aid,'openid'=>get_openid())))   $this->error('摄影师不存在!');
        return $data;
    }


    /*生成二维码*/
    private function createQRcode($save_path,$qr_data='PHP QR Code :)',$qr_level='L',$qr_size=4,$save_prefix='qrcode'){
        if(!isset($save_path)) return '';
        //设置生成png图片的路径
        $PNG_TEMP_DIR = & $save_path;
        //导入二维码核心程序
       vendor('phpqrcode.phpqrcode');
        //检测并创建生成文件夹
        if (!file_exists($PNG_TEMP_DIR)){
            mkdir($PNG_TEMP_DIR);
        }
        $filename = $PNG_TEMP_DIR.'test.png';
        $errorCorrectionLevel = 'L';
        if (isset($qr_level) && in_array($qr_level, array('L','M','Q','H'))){
            $errorCorrectionLevel = & $qr_level;
        }
        $matrixPointSize = 4;
        if (isset($qr_size)){
            $matrixPointSize = & min(max((int)$qr_size, 1), 10);
        }
        if (isset($qr_data)) {
            if (trim($qr_data) == ''){
                die('data cannot be empty!');
            }

            //生成文件名 文件路径+图片名字前缀+md5(名称)+.png
            $filename = $PNG_TEMP_DIR.$save_prefix.md5($qr_data.'|'.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';
            //开始生成
           \QRcode::png($qr_data, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
        } else {
            //默认生成
            \QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel, $matrixPointSize, 2,true);
        }
        if(file_exists($PNG_TEMP_DIR.basename($filename)))
            return basename($filename);
        else
            return FALSE;
    }
    //原图上传
    //原图上传
    public function upload()
    {
    	$data = $_POST['base64'];
    	preg_match("/data:image\/(.*);base64,/",$data,$res);
    	$ext = $res[1];
    	if(!in_array($ext,array("jpg","jpeg","png","gif"))){
    		echo json_encode(array("error"=>1));die;
    	}
    	//查询身份证号码
    	$card=D('Addons://Zmphoto/PhotoZmData')->getFie(array('id'=>$_POST['uid']),'card_id');
    	$file=$card.'.'.jpg;
    	$data = preg_replace("/data:image\/(.*);base64,/","",$data);
    	$path = getcwd();
    
    	if (file_put_contents($path."/Uploads/zmphoto/".$file,base64_decode($data))===false)
    	{
    
    		echo json_encode(array("error"=>1));
    	}
    	else
    	{
    		$data1['photo_gl'] =  D('Addons://Zmphoto/PhotoZmGl')->getFie(array('openid'=>get_openid()),'thumb');   //获取字段值
    		$data1['photo_url'] =  "./Uploads/zmphoto/".$file;
    		$model = D('Addons://Zmphoto/PhotoZmData');
    		if($model->update(array('id'=>$_POST['uid']),$data1)){
    			echo json_encode(array('src'=>"./Uploads/zmphoto/".$file,'size'=>$_POST['size'],"error"=>0));
    		}
    
    	}
    	 
    }
    //红蓝白
    public function upload1()
    {
    	$data = $_POST['base64'];
    	preg_match("/data:image\/(.*);base64,/",$data,$res);
    	$ext = $res[1];
    	if(!in_array($ext,array("jpg","jpeg","png","gif"))){
    		echo json_encode(array("error"=>1));die;
    	}
    	//查询身份证号码后6位
    	$card=D('Addons://Zmphoto/PhotoZmData')->getFie(array('id'=>$_POST['uid']),'card_id');
    	$file=substr($card,-6).time().'.'.jpg;
    	$data = preg_replace("/data:image\/(.*);base64,/","",$data);
    	$path = getcwd();
    
    	if (file_put_contents($path."/Uploads/rgb/".$file,base64_decode($data))===false)
    	{
    		echo json_encode(array("error"=>1));
    	}
    	else
    	{
    		$uid = $_POST['uid'];
    		$data1 ['photo_id'] = $uid;
    		$data1 ['path'] ="./Uploads/rgb/".$file;
    		$data1 ['status'] = 1;
    		$data1 ['create_time'] = time();
    		$electron = D('Addons://Zmphoto/Electron')->add($data1);
    		echo json_encode(array('src'=>"./Uploads/rgb/".$file,'size'=>$_POST['size'],"error"=>0,"id"=>$electron));
    	}
    
    }
    //我的电子照  红蓝白
    public function electron_pic()
    {
    	//         $isWeixinBrowser = isWeixinBrowser ();
    	//         if ($isWeixinBrowser) {
    	//             $this->error('请在微信打开');
    	//         }
    
    	if(IS_POST)
    	{
    		$data['size'] = $_POST['size'];
    		$data['photo_id'] = $_POST['photo_id'];
    		$data['remark'] = $_POST['remark'];
            $data['extract'] = $_POST['extract'];
    		$data['electron_id'] = $_POST['electron_id'];
    		$data['cost'] = $_POST['price'];
    		$data['openid'] = get_openid();
    		$data['status'] = 0;
    		$info = M('photo_zm_print')->add($data);
    		if($info)
    		{
    			$template = array('touser' => get_openid(),
    					'template_id' =>"5R-iUKrBsY2Pt5Bn0aYnU0oYPT73ordnEKEJ5rsiYyE",
    					'url' =>U('photo_print'),
    					'topcolor' => "#7B68EE",
    					'data' =>array(
    							'name'=>array('value'=>urlencode($_POST['size']),
    									'color'=>"#ff00000",
    							),
    							'remark'=>array('value'=>urlencode("\\n你的订单已提交，我们将尽快发货，祝您生活愉快！,如有疑問請加微信號：lyt10195"),
    									'color'=>"#008000",
    							),
    					)
    			);
    			send_template_message(urldecode(json_encode($template)));
    			$openid = array('oMaeHt-i1-3bi8Na8mhl1Ksh1ILA','oMaeHt9W8QBO3c0-NZ0l6k5Lb3sQ');
    			$num = count($openid);
    			for($i=0;$i<$num;++$i)
    			{
    
    				$template1 = array('touser' => $openid[$i],
    						'template_id' =>"1mS-7imTR3QnHJaiEFiMZUFie34fLnjaf42LqMWxZZ4",
    						'data' =>array(
    
    								'keyword1'=>array('value'=>urlencode($_POST['photo_id']),
    										'color'=>"#ff00000",
    								),
    								'keyword2'=>array('value'=>urlencode(date()),
    										'color'=>"#ff00000",
    								),
    								'keyword3'=>array('value'=>urlencode($_POST['price']),
    										'color'=>"#ff00000",
    								),
    								'keyword4'=>array('value'=>urlencode($_POST['size']),
    										'color'=>"#ff00000",
    								),
    								'keyword5'=>array('value'=>urlencode("未支付"),
    										'color'=>"#ff00000",
    								),
    								'remark'=>array('value'=>urlencode($_POST['remark']),
    										'color'=>"#008000",
    								),
    						)
    				);
    				send_template_message(urldecode(json_encode($template1)));
    			}
    			$map['status'] = 1;
    			$map['info'] = "提交成功";
    			$this->ajaxreturn($map);
    			//推送模版消息
    
    
    		}
    	}
    	$map['photo_id'] = I('get.uid');
    	$data = M('photo_zm_electron')->where($map)->select();
    	if($data == null)
    	{
    
    		$data = M('photo_zm_data')->where(array('id'=>I('get.uid')))->select();
    		foreach ($data as &$v)
    		{
    			$v['path'] = $v['photo_url'];
    			$v['id'] = 0;
    		}
    	}
    	$this->assign('data',$data);
    	$this->display();
    }
    //删除相片
    public function photo_del()
    {   $map['id'] = $_POST['id'];
    $data = M('photo_zm_electron')->where($map)->delete();
    }
    //在线打印
    
    public function photo_print()
    {
    	$map['openid'] = get_openid();
    	$userinfo = M('photo_zm_data')->where($map)->find();
    	$this->assign('user',$userinfo);
    	$print = M('photo_zm_print')->where($map)->select();
    	$this->assign('print',$print);
    	$this->display();
    }
    //完成支付
    public function print_finish()
    {
    	$data['pay_status'] = I('pay_type');
    	$data['pay_time'] = time();
    	M('photo_zm_print')->where(array('openid'=>get_openid()))->save($data);
    	$this->display();
    }


    public  function term_text_cn(){
        $this->display();
    }

}